package com.moshang.blog.controller.back.system;

import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.moshang.blog.core.annotation.SystemLog;
import com.moshang.blog.entity.SysRole;
import com.moshang.blog.entity.SysUser;
import com.moshang.blog.service.SysMenuService;
import com.moshang.blog.core.utils.PageUtil;
import com.moshang.blog.core.utils.RestResponse;
import com.moshang.blog.service.SysUsersService;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import com.moshang.blog.service.SysRoleService;
import org.springframework.web.util.WebUtils;

import javax.servlet.ServletRequest;


/**
 * 
 *
 * @author moshang
 * @email 597575122@qq.com
 * @date 2018-09-21 14:45:09
 */
@Controller
@RequestMapping("/back/system/role")
public class SysRoleController {
    @Autowired
    private SysRoleService sysRoleService;
    @Autowired
    private SysUsersService usersService;
    @Autowired
    private SysMenuService menuService;

    /**
     * 进入角色管理列表页面
     */
    @RequestMapping("/list")
    public String list(){

        return "back/system/role/list";
    }
    /**
     * 查询角色列表
     */
    @RequestMapping(value = "findList",method = RequestMethod.POST)
    @ResponseBody
    @ApiOperation(value = "/findList", httpMethod = "POST", notes = "查询角色列表")
    public PageUtil<SysRole> findList(@RequestParam(value = "page",defaultValue = "1")Integer page,
                                      @RequestParam(value = "limit",defaultValue = "10")Integer limit,
                                      ServletRequest request){
        Map map = WebUtils.getParametersStartingWith(request, "s_");
        PageUtil<SysRole> sysRolePageUtils = new PageUtil<>();
        QueryWrapper<SysRole> roleQueryWrapper = new QueryWrapper<>();
        roleQueryWrapper.eq("is_activited",0);
        if(!map.isEmpty()){
            String keys = (String) map.get("key");
            if(StringUtils.isNotBlank(keys)) {
                roleQueryWrapper.like("role_name", keys);
            }
        }
        IPage<SysRole> rolePage = sysRoleService.page(new Page<>(page,limit),roleQueryWrapper);
        sysRolePageUtils.setCount((int) rolePage.getTotal());
        sysRolePageUtils.setData(setUserToRole(rolePage.getRecords()));
        return sysRolePageUtils;

    }
    private List<SysRole> setUserToRole(List<SysRole> roles){
        for(SysRole r : roles){
            if(r.getCreateBy() != null && r.getCreateBy() != 0){
                SysUser u = usersService.findUserById(r.getCreateBy());
                r.setCreateName(u.getUserName());
            }
            if(r.getUpdateBy() != null && r.getUpdateBy() != 0){
                SysUser u  = usersService.findUserById(r.getUpdateBy());

                r.setUpdateName(u.getUserName());
            }
        }
        return roles;
    }

    /**
     * 进入添加角色页面
     * @param model
     * @return
     */
    @GetMapping(value = "/addUI")
    public String addUI(Model model) {
        JSONArray jsonArray = menuService.getTreeUtil(null);
        model.addAttribute("menus", jsonArray);
        return "back/system/role/add";
    }

    /**
     * 添加角色
     * @param role
     * @return
     */
    @RequiresPermissions("sys:role:add")
    @PostMapping("add")
    @ResponseBody
    @SystemLog("保存新增角色数据")
    @ApiOperation(value = "/add", httpMethod = "POST", notes = "添加角色")
    public RestResponse add(SysRole role,@RequestParam(value = "menus[]",required = false)Integer[] menus){
        if(StringUtils.isBlank(role.getRoleName())){
            return RestResponse.failure("角色名称不能为空");
        }
        if(sysRoleService.getRoleNameCount(role.getRoleName())>0){
            return RestResponse.failure("角色名称已存在");
        }
        sysRoleService.saveRole(role,menus);
        return RestResponse.success();
    }
    /**
     * 进入角色编辑页面
     */
    @RequestMapping("/editUI")
    public String editUI(@RequestParam("id") Long id, Model model){
        SysRole sysRole=sysRoleService.getById(id);
        model.addAttribute("role",sysRole);
        JSONArray jsonArray = menuService.getTreeUtil(id);
        model.addAttribute("menus", jsonArray);
        return "back/system/role/edit";
    }
    @RequiresPermissions("sys:role:edit")
    @PostMapping("edit")
    @ResponseBody
    @SystemLog("保存编辑角色数据")
    @ApiOperation(value = "/edit", httpMethod = "POST", notes = "修改角色")
    public RestResponse edit(SysRole role,@RequestParam(value = "menus[]",required = false) Integer[] menus){
        if(role.getId() == null || role.getId() == 0){
            return RestResponse.failure("角色ID不能为空");
        }
        if(StringUtils.isBlank(role.getRoleName())){
            return RestResponse.failure("角色名称不能为空");
        }
        SysRole oldRole = sysRoleService.getById(role.getId());
        if(!oldRole.getRoleName().equals(role.getRoleName())){
            if(sysRoleService.getRoleNameCount(role.getRoleName())>0){
                return RestResponse.failure("角色名称已存在");
            }
        }
        sysRoleService.updateRole(role,menus);
        return RestResponse.success();
    }
    @RequiresPermissions("sys:role:delete")
    @PostMapping("delete")
    @ResponseBody
    @SystemLog("删除角色")
    @ApiOperation(value = "/delete", httpMethod = "POST", notes = "删除角色")
    public RestResponse deleteById(@RequestParam("id") Integer id){
        if(id == null || id == 0){
            return RestResponse.failure("角色ID不能为空");
        }
        SysRole role = sysRoleService.getById(id);
        sysRoleService.deleteRole(role);
        return RestResponse.success();
    }
    @RequiresPermissions("sys:role:edit")
    @PostMapping("batchDelete")
    @ResponseBody
    @SystemLog("批量删除角色")
    @ApiOperation(value = "/batchDelete", httpMethod = "POST", notes = "批量删除角色")
    public RestResponse batchDelete(@RequestBody List<SysRole> roles){
        if(roles == null || roles.size() == 0){
            return RestResponse.failure("请选择需要删除的角色");
        }
        for (SysRole sysRole:roles){
            SysRole role = sysRoleService.getById(sysRole.getId());
            sysRoleService.deleteRole(role);
        }

        return RestResponse.success();
    }
    @ApiOperation(value = "/showRoleList", httpMethod = "GET", notes = "展示角色")
    @GetMapping(value = "showRoleList")
    @ResponseBody
    public String showRoleList(SysRole role, Model model) {
        return sysRoleService.showAll(role);
    }
}
